package com.house.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.house.utils.JsonOutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 小贾
 * @version 1.0
 * @description: TODO
 * @date 2025/9/17 16:29
 */
@RestController
@RequestMapping("uploadOssFile")
public class OssFileController {
    @Autowired
    private OSS ossClient;

    @PostMapping("putObject")
    public JsonOutputUtil<List<Bucket>> putObject(MultipartFile file) throws IOException {
        //查询所有的桶的列表
        List<Bucket> buckets = ossClient.listBuckets();
        //上传数据
        ossClient.putObject("tpfangjys", file.getOriginalFilename(), file.getInputStream());
        return new JsonOutputUtil<>(buckets);
    }

    @PostMapping("getObject")
    public JsonOutputUtil<Object> getObject(MultipartFile file) {

        String filePath = "D:\\浏览器\\" + UUID.randomUUID().toString() + ".pdf";
        //下载数据
        ossClient.getObject(new GetObjectRequest("tpfangjys", "加水印.pdf"), new File(filePath));

        return new JsonOutputUtil<>("");
    }

    @GetMapping("getUrl")
    public JsonOutputUtil<Object> getUrl() throws IOException {
        //构造参数
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest("tpfangjys", "加水印.pdf", HttpMethod.GET);
        //过期时间
        Date expiration = new Date(new Date().getTime() + 1000 * 60 * 2);
        req.setExpiration(expiration);

        //生成url
        URL url = ossClient.generatePresignedUrl(req);

        return new JsonOutputUtil<>(url);
    }
}
